package com.wencst.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;

import com.wencst.security.handler.MyUserDetailsService;
/**
 * spring security 服务配置类
 * @author wencst
 *
 */
@Configuration
public class BrowerSecurityConfig extends WebSecurityConfigurerAdapter {
	@Autowired
	private AccessDeniedHandler accessDeniedHandler;

	@Autowired
	MyUserDetailsService myUserDetailsService;
	
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    	System.out.println("web security configuration gw");
        http.formLogin()                    //  定义当需要用户登录时候，转到的登录页面。
        .loginPage("/login")           // 设置登录页面
//        .defaultSuccessUrl("/users",true)
        .loginProcessingUrl("/user/login")  // 自定义的登录接口，不设置此URL，login方法不走userdetailservice方法？
        .and()
        .authorizeRequests()        // 定义哪些URL需要被保护、哪些不需要被保护
//        .antMatchers("/", "/home").access("hasRole('USER') and hasRole('ADMIN') or hasRole('DBA')") //此用法可以用Spring EL表达式
        .antMatchers("/login","/user/login",
        		"*.css","*.js","*.html",
        		"*.eot","*.svg","*.ttf","*.woff",
        		"/layui/**","/module/**","/css/**","/js/**").permitAll()     // 设置所有人都可以访问登录页面
        .anyRequest()               // 任何请求,登录后可以访问
        .authenticated()
        .and()
		.logout().logoutSuccessUrl("/login").permitAll()
		.and()
		.exceptionHandling().accessDeniedHandler(accessDeniedHandler)
		.and()
        .csrf().disable()          // 关闭csrf防护
    	.headers().frameOptions().sameOrigin();//解决iframe无法打开页面问题
    }
    /**
     * 增加密码加密
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
         return new BCryptPasswordEncoder();
    }
    
}